<?php

namespace app\controllers;

use Yii;
use app\models\News;
use app\models\NewsSearch;
use app\models\NewsCategory;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\Sort;
// use yii\data\ArrayDataProvider;
// use yii\data\Pagination;

/**
 * NewsController implements the CRUD actions for News model.
 */
class NewsController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            // 'verbs' => [
            //     'class' => VerbFilter::className(),
            //     'actions' => [
            //         'delete' => ['POST'],
            //     ],
            // ],
            'login' => [
                'class'   => \app\filters\LoginFilter::className()
            ],
        ];
    }

    /**
     * Lists all News models.
     * @return mixed
     */
    public function actionIndex()
    {   
        
        // 获取当前请求页的每一行数据
        // $rows = $provider->getModels();
        $searchModel = new NewsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $newsCategory = new NewsCategory;

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'newsCategory' =>$newsCategory,
        ]);
    }

    /**
     * Displays a single News model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new News model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new News();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing News model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing News model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    //更改审核状态
    public function actionUpdateCheckStatus(){
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $post_data = \Yii::$app->request->post('News', 0);
        $id = $post_data['id'];
        $status = $post_data['status'];
        // return ['data' => [$id]];
        $model = $this->findModel($id);
        if ($model->status == $status) {
            return array('ok' => -1, 'message' => '不能修改重复状态');
        }

        $model->status = $status;
        $model->opt_note = $post_data['opt_note'];

        if (!$model->save()) {
            $error = current($model->getErrors());
            return array('ok' => -1, 'message' => '修改状态失败:'.$error[0]);
        }

        return array('ok' => 0, 'message' => '修改成功！');
    }

    //审核弹框
    public function actionCheck($id){
        $model = $this->findModel($id);
        return $this->renderAjax('check_form', [
            'model' => $model,
            'data' => $model::getCheckStatusKeyPair('name'),
        ]);
    }


    /**
     * Finds the News model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return News the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = News::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    //批量导入项目
    public function actionBatchUpload(){
        $project = new News;
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        // echo '<pre>';
        //     print_r($_FILES["file"]);die;
        if(!isset($_FILES["file"])){
            return [
                'code' => 1,
                'message' => '请上传文件'
            ];
        }
        if($_FILES["file"]["error"] > 0){
            return [
                'code' => 1,
                'message' => '文件上传失败,请重新上传'
            ];
        }

        if($_FILES["file"]["type"] != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
            return [
                'code' => 1,
                'message' => '文件格式不对'
            ];
        }

        //临时文件名称
        $excelFile= $_FILES['file']['tmp_name'];

        require Yii::getAlias("@web").'../helpers/PHPExcel.php';
        $excelReader = \PHPExcel_IOFactory::createReader('Excel2007');//xslx格式的
        $phpexcel = $excelReader->load($excelFile)->getSheet(0);//载入文件并获取第一个sheet
        $total_line = $phpexcel->getHighestRow();            //多少行
        // $total_line = 2;            //多少行

        $transaction = \Yii::$app->db->beginTransaction();

        $pro_cate = NewsCategory::find()->indexBy('id')->asArray()->all();

        //获取本分类ID下面最大的排序数
        for($row = 2; $row <= $total_line; $row++) {
            $columnInfo  = $countries = array();
            for($column = 'A'; $column <= 'P'; $column++) {
                $columnInfo[] = trim($phpexcel->getCell($column.$row)->getValue());
            }
            if(!trim($columnInfo[0])) continue;

            $_import_data['title'] = addslashes($columnInfo[0]);
            $_import_data['category'] = array_rand($pro_cate);//测试用
            $_import_data['brief_desc'] = addslashes($columnInfo[2]);
            $_import_data['desc'] = addslashes($columnInfo[3]);
            $_import_data['cover'] = addslashes($columnInfo[4]);
            $_import_data['label'] = $columnInfo[5];

            // $_import_data['progress'] = empty($columnInfo[10]) ? 0 : $columnInfo[10];
            $_import_data['status'] = News::CHECK_STATUS_PASS;
            $_import_data['opt_note'] = '后台导入的';
            $_import_data['author'] = 0;//暂用0表示后台导入
            $_import_data['created_time'] = time();


            $sql = "REPLACE INTO  ww2_news (title,category,brief_desc,`desc`,cover,label,status,opt_note,author,created_time) VALUES ('{$_import_data['title']}','{$_import_data['category']}','{$_import_data['brief_desc']}','{$_import_data['desc']}','{$_import_data['cover']}','{$_import_data['label']}','{$_import_data['status']}','{$_import_data['opt_note']}','{$_import_data['author']}',{$_import_data['created_time']})";
            $command = \Yii::$app->db->createCommand($sql);
 
            if (!$command->execute()) {
                $transaction->rollBack();
                $error = $project->getErrors();
                return [
                    'code' => 1,
                    'message' => current($error)[0],
                ];
            }
        }

        $transaction->commit();

        return [
            'code' => 0,
            'message' => '导入成功！'
        ];
        
    }
}
